<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="图号" prop="drawingNo">
            <el-input v-model="formData.drawingNo" placeholder="请输入图号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户名" prop="customer">
            <el-input v-model="formData.customer" placeholder="请输入客户名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模具类型" prop="categoryId">
            <el-tree-select v-model="formData.categoryId" :data="categoryTree" :props="defaultProps" check-strictly
              filterable clearable default-expand-all placeholder="请选择模具类型" value-key="id" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="保养类型" prop="upkeepId">
            <el-select v-model="formData.upkeepId" filterable clearable placeholder="请选择保养类型" style="width: 100%;">
              <el-option v-for="upkeepcategory in upkeepList" :key="upkeepcategory.id" :label="upkeepcategory.name"
                :value="upkeepcategory.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="复检类型" prop="recheckId">
            <el-select v-model="formData.recheckId" filterable clearable placeholder="请选择复检类型" style="width: 100%;">
              <el-option v-for="recheck in recheckList" :key="recheck.id" :label="recheck.name" :value="recheck.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="寿命扣减方式" prop="lifeDeductionId">
            <el-select v-model="formData.lifeDeductionId" placeholder="请选择寿命扣减方式">
              <el-option label="自动" :value="1" />
              <el-option label="手动" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="默认库存状态" prop="inventoryStatus">
            <el-select v-model="formData.inventoryStatus" placeholder="请选择库存状态">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MOLD_INVENTORY_STATUS)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="默认绑定设备" prop="devId">
            <el-select :loading="remortLoading" remote :remote-method="remoteSearch" clearable filterable
              v-model="formData.devId" placeholder="请输入至少3个字符搜索设备">
              <el-option v-for="dict in EquipmentList" :key="dict.id"
                :label="`${dict.equipmentName} - ${dict.code} - ${dict.installPosition}`" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入库人员" prop="warehouseInPersonId">
            <el-select v-model="formData.warehouseInPersonId" filterable clearable placeholder="入库人员"
              style="width: 100%;">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="入库时间" prop="warehouseInTime">
            <el-date-picker v-model="formData.warehouseInTime" type="datetime" value-format="x" placeholder="选择入库时间"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出库人员" prop="warehouseOutPersonId">
            <el-select v-model="formData.warehouseOutPersonId" filterable clearable placeholder="出库人员"
              style="width: 100%;">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出库时间" prop="warehouseOutTime">
            <el-date-picker v-model="formData.warehouseOutTime" type="datetime" value-format="x" placeholder="选择出库时间"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="默认仓库/储位" required>
        <el-row :gutter="10" style="width: 100%">
          <el-col :span="5">
            <el-select v-model="formData.warehouseId" filterable clearable @change="handleWarehouseChange"
              placeholder="请选择仓库">
              <el-option v-for="warehouse in warehouseList" :key="warehouse.id"
                :label="`${warehouse.code} - ${warehouse.name}`" :value="warehouse.id" />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="formData.storageId" filterable clearable placeholder="请选择储位">
              <el-option v-for="storage in filteredStorageList" :key="storage.id"
                :label="`${storage.code} - ${storage.name}`" :value="storage.id" />
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <Editor v-model="formData.description" height="150px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import { DrawingNoApi, DrawingNo } from '@/api/mold/drawingno'
import { CategoryApi } from '@/api/mold/category'
import { UpkeepCategoryApi } from '@/api/mold/upkeepcategory'
import { RecheckCategoryApi } from '@/api/mold/recheckcategory'
import type { UserVO } from '@/api/system/user'
import { get } from 'http'
import * as UserApi from '@/api/system/user'
import { WarehouseApi, Warehouse } from '@/api/mold/warehouse'
import { StorageApi, Storage } from '@/api/mold/storage'
import { EquipmentManageApi, EquipmentManage } from '@/api/business/equipmentmanage'

/** 模具图号 表单 */
defineOptions({ name: 'DrawingNoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  drawingNo: undefined,
  customer: undefined,
  categoryId: undefined,
  upkeepId: undefined,
  recheckId: undefined,
  lifeDeductionId: undefined,
  inventoryStatus: undefined,  // 修改字段名
  warehouseId: undefined,
  storageId: undefined,
  devId: undefined,
  warehouseInPersonId: undefined,
  warehouseInTime: undefined,
  warehouseOutPersonId: undefined,
  warehouseOutTime: undefined,
  description: undefined,
})
const formRules = reactive({
  drawingNo: [{ required: true, message: '图号不能为空', trigger: 'blur' }],
  upkeepId: [{ required: true, message: '保养类型id不能为空', trigger: 'change' }],
  categoryId: [{ required: true, message: '模具类型id不能为空', trigger: 'blur' }],
  lifeDeductionId: [{ required: true, message: '寿命扣减方式id不能为空', trigger: 'change' }],
  inventoryStatus: [{ required: true, message: '库存状态不能为空', trigger: 'change' }],  // 修改验证规则
})
const formRef = ref() // 表单 Ref
// 新增选中的仓库ID
const selectedWarehouse = ref<number>()
// 过滤后的储位列表
const filteredStorageList = ref<Storage[]>([])
const userList = ref<UserVO[]>([])
const warehouseList = ref<Warehouse[]>([])
const storageList = ref<Storage[]>([])
const categoryTree = ref()
const upkeepList = ref()
const recheckList = ref()
const remortLoading = ref(false)
//设备列表
const EquipmentList = ref([])

/** 获得模具类型树 */
const getCategoryTree = async () => {
  categoryTree.value = []
  const data = await CategoryApi.getCategoryAll()
  categoryTree.value = handleTree(data)
  console.log(categoryTree.value)
}


/** 获得保养类型树 */
const getUpkeepList = async () => {
  upkeepList.value = []
  const data = await UpkeepCategoryApi.getUpkeepCategoryAll()
  upkeepList.value = handleTree(data)
}

/** 获得复检类型树 */
const getRecheckList = async () => {
  recheckList.value = []
  const data = await RecheckCategoryApi.getRecheckCategoryAll()
  recheckList.value = handleTree(data)
  console.log(recheckList.value)
}


const getUserList = async () => {
  userList.value = await UserApi.getSimpleUserList()
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  warehouseList.value = await WarehouseApi.getWarehouses()
  storageList.value = await StorageApi.getStorageAll()
  getUserList()
  getCategoryTree()
  getUpkeepList()
  getRecheckList()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DrawingNoApi.getDrawingNo(id)
      // 设置仓库选择
      if (formData.value.storageId) {
        const storage = storageList.value.find(s => s.id === formData.value.storageId)
        if (storage && storage.warehouseId) {
          selectedWarehouse.value = storage.warehouseId
          formData.value.warehouseId = storage.warehouseId
          // 触发一次过滤储位列表
          handleWarehouseChange(storage.warehouseId, true)
        }
      }

      // ADD: 如果有绑定设备ID，创建一个包含设备信息的对象以在选择器中显示
      if (formData.value.devId && formData.value.devName) {
        // 创建一个临时对象以显示设备信息
        const deviceInfo = {
          id: formData.value.devId,
          equipmentName: formData.value.devName,
          code: formData.value.devCode,
          installPosition: formData.value.devPosition
        };

        // 将设备信息添加到设备列表中（如果尚不存在）
        if (!EquipmentList.value.some(item => item.id === deviceInfo.id)) {
          EquipmentList.value.push(deviceInfo);
        }
      }


    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 处理仓库选择变化
const handleWarehouseChange = (warehouseId: number, isEdit = false) => {
  if (warehouseId) {
    filteredStorageList.value = storageList.value.filter(storage => storage.warehouseId === warehouseId)
  } else {
    filteredStorageList.value = []
  }
  // 只有在非编辑状态下才清除已选择的储位
  if (!isEdit) {
    formData.value.storageId = undefined
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DrawingNo
    if (formType.value === 'create') {
      await DrawingNoApi.createDrawingNo(data)
      message.success(t('common.createSuccess'))
    } else {
      await DrawingNoApi.updateDrawingNo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    drawingNo: undefined,
    customer: undefined,
    categoryId: undefined,
    upkeepId: undefined,
    recheckId: undefined,
    lifeDeductionId: undefined,
    inventoryStatus: undefined,
    warehouseId: undefined,
    storageId: undefined,
    devId: undefined,
    warehouseInPersonId: undefined,
    warehouseInTime: undefined,
    warehouseOutPersonId: undefined,
    warehouseOutTime: undefined,
    description: undefined,
  }
  formRef.value?.resetFields()
  // 重置过滤后的储位列表
  filteredStorageList.value = []
}


const remoteSearch = async (query) => {
  // 修改为超过2个字符才执行搜索
  if (query && query.length > 2) {
    remortLoading.value = true
    let params = {
      keyWords: query
    }
    EquipmentList.value = await EquipmentManageApi.getEquipmentManageList(params)
    remortLoading.value = false
  } else {
    // 如果查询关键字为空或长度不足，清空结果列表
    EquipmentList.value = []
  }
}
</script>